import os

import pandas as pd
from catboost import CatBoostClassifier
from xbase_util.common_util import check_path

from src.bean.model_database_enum import ModelDatabaseEnum
from src.constant import project_root_path
from src.model.model_common_util import get_model
from src.util.common_util import printx
from src.util.config_manager import ConfigManager


def importance_to_file_entrance(config: ConfigManager) -> None:
    old_model = get_model(config)
    if old_model is None:
        return
    model = CatBoostClassifier()
    model.load_model(old_model[ModelDatabaseEnum.model_path.value])
    importance_values = model.get_feature_importance()
    # 获取特征名称
    feature_names = model.feature_names_
    importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importance_values})
    # 按重要性排序
    importance_df = importance_df.sort_values(by='Importance', ascending=False)
    # 生成文件路径
    importance_path = os.path.join(project_root_path, 'model',
                                   f'importance_{old_model[ModelDatabaseEnum.id.value]}.csv')
    importance_df.to_csv(check_path(importance_path), index=False)
    printx("特征重要性:")
    printx(importance_df)
    printx(f"已输出相关性到: {importance_path}")
